<template>
  <div style="width: 256px">
    <a-menu
      :selected-keys="selectedKeys"
      :open-keys.sync="openKeys"
      mode="inline"
      :theme="theme"
    >
      <template v-for="item in menuData">
        <a-menu-item
          v-if="!item.children"
          :key="item.path"
          @click="
            () =>
              item.path != $route.path &&
              $router.push({ path: item.path, query: $route.query })
          "
        >
          <a-icon v-if="item.meta.icon" :type="item.meta.icon" />
          <span>{{ item.meta.title }}</span>
        </a-menu-item>
        <sub-menu v-else :key="item.path" :menu-info="item" />
      </template>
    </a-menu>
  </div>
</template>

<script>
import SubMenu from "./SubMenu";
import { check } from "@/utils/auth";
export default {
  components: {
    "sub-menu": SubMenu
  },
  props: {
    theme: {
      type: String,
      default: "dark"
    },
    sideCollapsed: {
      type: Boolean,
      default: false
    }
  },
  data() {
    this.selectedKeysMap = {};
    this.openKeysMap = {};
    let menuData = this.getMenuData(this.$router.options.routes);
    return {
      collapsed: false,
      menuData,
      selectedKeys: this.selectedKeysMap[this.$route.path],
      openKeys: this.collapsed ? [] : this.openKeysMap[this.$route.path]
    };
  },
  watch: {
    "$route.path": function(val) {
      this.selectedKeys = this.selectedKeysMap[val];
      this.openKeys = this.collapsed ? [] : this.openKeysMap[val];
    },
    sideCollapsed: function(newVal) {
      this.openKeys = newVal ? [] : this.openKeysMap[this.$route.path];
    }
  },
  methods: {
    // 自动会更新collapsed值
    // toggleCollapsed() {
    //   this.collapsed = !this.collapsed;
    // },
    getMenuData(routes, parentKeys = [], selectedKey) {
      let menuData = [];
      routes.forEach(item => {
        if (item.meta && item.meta.authority && !check(item.meta.authority)) {
          return;
        }
        if (item.hideInMenu) {
          return;
        }
        if (!(item.name || item.children)) {
          return;
        }
        this.openKeysMap[item.path] = parentKeys;
        this.selectedKeysMap[item.path] = [selectedKey || item.path];
        let newItem = { ...item };
        if (item.children) {
          delete newItem.children;
          if (!item.hideChildrenInMenu) {
            newItem.children = this.getMenuData(item.children, [
              ...parentKeys,
              item.path
            ]);
          } else {
            this.getMenuData(
              item.children,
              selectedKey ? parentKeys : [...parentKeys, item.path],
              selectedKey || item.path
            );
          }
        }
        if (item.name) {
          menuData.push(newItem);
        } else {
          menuData.push(...newItem.children);
        }
      });
      return menuData;
    }
  }
};
</script>
